<?php
/**
 * Export.php
 * description:
 * Created by www.
 * User: SCF
 * Date: 2018/11/9 10:00
 *
 */

namespace common\utils;


class Export
{
    public static function exportExcel($file_name, $labels, $data,$total)
    {
        set_time_limit(0);
        $file_name = strpos($file_name, '.csv') ? $file_name : $file_name . '.csv';
        header ( "Content-type:application/vnd.ms-excel" );
        header ( "Content-Disposition:filename=" . iconv ( "UTF-8", "GB18030", $file_name ) );
        $openf = fopen('php://output', 'w');
        foreach ($labels as $i => $v) {
            $labels[$i] = iconv('utf-8', 'GB18030', $v);
        }
        //输出头部
        fputcsv($openf, $labels);
        //输出内容
        foreach ( $data as $item ) {
            $rows = array();
            foreach ( $labels as $key=>$val){
                $rows[] = isset($item[$key]) ? iconv('utf-8', 'GB18030', $item[$key] . "\t") : "";
            }
            fputcsv($openf, $rows);
        }
        if($total == 'null'){
            $rs[] = iconv('utf-8', 'GB18030', '总计:'.count($data));
        }else{
            $n = count ($labels);
            $k = count ($total);
            for ($i=0;$i<$n-$k;$i++){
                if ($i ==0 ){
                    $rs[$i] = iconv('utf-8', 'GB18030', '总计:');
                    continue;
                }
                $rs[$i] = iconv('utf-8', 'GB18030', '');
            }
            foreach ($total as $t){
                $rs[$i] = iconv('utf-8', 'GB18030', $t);
                $i ++ ;
            }

        }
        fputcsv($openf, $rs);
        if( ob_get_level() > 0 ) ob_flush();
        flush();
        exit;
    }
}